﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WpfSnqkGasAnalysis.Common;
using WpfSnqkGasAnalysis.Model;
using WpfSnqkGasAnalysis.IBusiness_impl;
using System.Text.RegularExpressions;
using System.Windows.Interop;

namespace WpfSnqkGasAnalysis
{
    /// <summary>
    /// 特殊报告。编辑
    /// </summary>
    /// 创建时间：2022-12-21 16:58:12。作者：王浩力
    public partial class WindowTeshuGasEdit : Window
    {
        public WindowTeshuGasEdit()
        {
            InitializeComponent();
        }

        internal Teshu_gas TeshuGas { get; set; }

        TeshuBusiness teshuBusiness = new TeshuBusiness();
        SourceDictBusiness sourceDictBusiness = new SourceDictBusiness();
        UserBusiness userBusiness = new UserBusiness();

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //添加时间：2023-1-8 23:47:13。
            var userList = userBusiness.GetAllUser();
            userList = userList.FindAll(g => g.U_stat == 1);

            if (TeshuGas.E12 == 226)
            {
                //校对
                this.Title = "特殊报告校对";
                btnSave.Visibility = Visibility.Collapsed;
            }
            else
            {
                //编辑
                btnJiaoDui.Visibility = Visibility.Collapsed;
            }

            //禁用关闭按钮
            int handle = new WindowInteropHelper(this).Handle.ToInt32();
            WinodowCloseButtonSet.Disable(handle);

            var list = sourceDictBusiness.GetAll();
            list = list.FindAll(g => g.D_stat == 1);

            //委托单位 cmb_client
            cmb_client.ItemsSource = list.FindAll(x => x.Group_id.Equals("quyang"));
            cmb_client.DisplayMemberPath = "Item_name";
            cmb_client.SelectedValuePath = "Id";

            //取样单位 cmb_sampling_unit
            cmb_sampling_unit.ItemsSource = list.FindAll(x => x.Group_id.Equals("quyang"));
            cmb_sampling_unit.DisplayMemberPath = "Item_name";
            cmb_sampling_unit.SelectedValuePath = "Id";

            //顶界层位 cmb_top_boundary
            cmb_top_boundary.ItemsSource = list.FindAll(g => g.Group_id.Equals("cengwei"));
            cmb_top_boundary.DisplayMemberPath = "Item_name";
            cmb_top_boundary.SelectedValuePath = "Id";

            //取样人 cmb_sampler
            cmb_sampler.ItemsSource = userList;
            cmb_sampler.DisplayMemberPath = "User_real_name";
            cmb_sampler.SelectedValuePath = "Id";

            //底界层位 cmb_bottom_boundary
            cmb_bottom_boundary.ItemsSource = list.FindAll(g => g.Group_id.Equals("cengwei"));
            cmb_bottom_boundary.DisplayMemberPath = "Item_name";
            cmb_bottom_boundary.SelectedValuePath = "Id";

            //取样位置  cmb_sampling_location
            cmb_sampling_location.ItemsSource = list.FindAll(g => g.Group_id.Equals("quyangLocation"));
            cmb_sampling_location.DisplayMemberPath = "Item_name";
            cmb_sampling_location.SelectedValuePath = "Id";

            //分析人   cmb_analyst
            cmb_analyst.ItemsSource = userList;
            cmb_analyst.DisplayMemberPath = "User_real_name";
            cmb_analyst.SelectedValuePath = "Id";

            //采样时间初始化。
            date_sampling_time.SelectedDateTime = DateTime.Now;


            //编辑赋值
            this.txt_report_no.Text = TeshuGas.Report_no;
            this.txt_well_no.Text = TeshuGas.Well_no;
            this.txt_well_deep.Text = TeshuGas.Well_deep.ToString();

            this.txtSample_temperature.Text = TeshuGas.Sample_temperature.ToString();
            this.txtOil_pressure.Text = TeshuGas.Oil_pressure.ToString();
            this.cmb_client.SelectedValue = TeshuGas.Client;
            this.cmb_sampling_unit.SelectedValue = TeshuGas.Sampling_unit;

            this.cmb_top_boundary.SelectedValue = TeshuGas.Top_boundary;
            this.cmb_bottom_boundary.SelectedValue = TeshuGas.Bottom_boundary;
            this.txt_casing_pressure.Text = TeshuGas.Casing_pressure.ToString();

            //修改时间：2023-1-15 18:10:25。
            if (!string.IsNullOrWhiteSpace(TeshuGas.Sampler) && Regex.IsMatch(TeshuGas.Sampler, "^\\d{1,19}"))
            {
                this.cmb_sampler.SelectedValue = TeshuGas.Sampler;//取样人
            }

            this.date_sampling_time.SelectedDateTime = Convert.ToDateTime(TeshuGas.Sampling_time);

            //取样位置；修改时间：2023-1-15 18:31:25
            if (Regex.IsMatch(TeshuGas.Sampling_location, "^\\d{1,19}"))
            {
                this.cmb_sampling_location.SelectedValue = TeshuGas.Sampling_location;
            }
            else
            {
                this.txt_sampling_location2.Text = TeshuGas.Sampling_location;
            }


            //分析人
            if (!string.IsNullOrWhiteSpace(TeshuGas.Analyst) && Regex.IsMatch(TeshuGas.Analyst, "^\\d{1,19}"))
            {
                this.cmb_analyst.SelectedValue = TeshuGas.Analyst;
            }


            //查询子项列表 ，添加时间：2022-12-21 16:41:55
            var itemList = teshuBusiness.GetTeshu_gas_itemList(TeshuGas.Id);
            this.listView.ItemsSource = itemList;

            date_sampling_time.MoveFocus(new TraversalRequest(FocusNavigationDirection.First));
        }

        //保存
        private void save_Click(object sender, RoutedEventArgs e)
        {
            //取样位置 ，添加时间：2023-1-15 18:18:33。作者：王浩力
            string sampling_location2 = cmb_sampling_location.SelectedValue?.ToString();
            if (!string.IsNullOrWhiteSpace(txt_sampling_location2.Text.Trim()))
            {
                sampling_location2 = txt_sampling_location2.Text.Trim();
            }

            Teshu_gas teshu_Gas = new Teshu_gas();
            teshu_Gas.Id = TeshuGas.Id;
            teshu_Gas.Report_no = txt_report_no.Text.Trim();
            teshu_Gas.Sample_temperature = txtSample_temperature.Text.Trim().ToMyDecimal();
            teshu_Gas.Oil_pressure = txtOil_pressure.Text.Trim().ToMyDecimal();
            teshu_Gas.Client = cmb_client.SelectedValue?.ToString();
            teshu_Gas.Sampling_unit = cmb_sampling_unit.SelectedValue?.ToString();

            teshu_Gas.Well_no = txt_well_no.Text.Trim();
            teshu_Gas.Top_boundary = cmb_top_boundary.SelectedValue?.ToString();
            teshu_Gas.Casing_pressure = txt_casing_pressure.Text.Trim().ToMyDecimal();
            teshu_Gas.Sampler = cmb_sampler.SelectedValue?.ToString();
            teshu_Gas.Sampling_time = date_sampling_time.Text;

            teshu_Gas.Well_deep = txt_well_deep.Text.Trim().ToString();
            teshu_Gas.Bottom_boundary = cmb_bottom_boundary.SelectedValue?.ToString();
            //teshu_Gas.Sampling_location = cmb_sampling_location.SelectedValue?.ToString();
            teshu_Gas.Sampling_location = sampling_location2;

            teshu_Gas.Analyst = cmb_analyst.SelectedValue?.ToString();

            //保存主表记录
            var result = teshuBusiness.Edit(teshu_Gas);
            ShowAlertHelpter.ShowAlert("主记录" + result.Msg);

            RefreshPageList?.Invoke(this, e);

            //Snowflake snowflake = new Snowflake(1, 1);
            //teshu_gasKEY = snowflake.NextId();
        }

        /// <summary>
        /// 刷新父页面，列表分页
        /// </summary>
        public event EventHandler RefreshPageList;

        // 退出
        private void saveExit_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }


        ///(继续添加) teshu_gas_item 特殊气报告项，检测值
        private void teshu_gas_itemAdd_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txt_report_no.Text.Trim()))
            {
                ShowAlertHelpter.ShowAlert("请先输入上半部分的主要信息，保证都填写完");
                e.Handled = true;
                return;
            }

            //打开添加项，窗口
            WindowTeshuItemAdd windowTeshuItemAdd = new WindowTeshuItemAdd();
            windowTeshuItemAdd.teshuGasKey = TeshuGas.Id;
            windowTeshuItemAdd.RefreshParentWindowListData += WindowTeshuItemAdd_RefreshParentWindowListData;
            windowTeshuItemAdd.ShowDialog();
        }

        //刷新特殊报告子项表格
        private void WindowTeshuItemAdd_RefreshParentWindowListData(object? sender, EventArgs e)
        {
            var list = teshuBusiness.GetTeshu_gas_itemList(TeshuGas.Id);
            this.listView.ItemsSource = list;
        }

        //检查输入字符串是否为数字 //创建时间：2022-12-7 15:16:20，作者：王浩力
        private void numberCheck_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            var textElem = (sender as TextBox);

            //解决连续输入很多.
            if ((
                textElem.Text.StartsWith(".") || string.IsNullOrWhiteSpace(textElem.Text)
                || textElem.Text.Contains(".")
                ) && e.Text == ".")
            {
                e.Handled = true;
                return;
            }

            //禁止在0前面继续输入0
            int index = ((System.Windows.Controls.TextBox)e.Source).CaretIndex;
            if (textElem.Text.StartsWith("0.") && index == 0 && e.Text == "0")
            {
                e.Handled = true;
                return;
            }

            //不能输入非数字
            if (Regex.IsMatch(e.Text, @"[^\d+\.{0,1}\d+]+"))
            {
                e.Handled = true;
                return;
            }
        }

        //检查输入字符串是否为数字 //创建时间：2022-12-7 15:16:20，作者：王浩力
        private void numberCheck_PreviewKeyUp(object sender, KeyEventArgs e)
        {
            TextBox textBox = sender as TextBox;
            if (!string.IsNullOrWhiteSpace(textBox.Text))
            {
                if (textBox.Text == "0.0" || textBox.Text.StartsWith("00"))
                {
                    textBox.Text = textBox.Text.Replace("00", "");
                }
                if (!textBox.Text.StartsWith("0.") && Regex.IsMatch(textBox.Text, @"0+[1-9]+\.*\d+", RegexOptions.IgnoreCase))
                {
                    textBox.Text = textBox.Text.TrimStart('0');
                }

                //输入的不是小数或正整数           
                Regex regex = new Regex(@"[^\d+\.{0,1}\d+]", RegexOptions.IgnoreCase);
                textBox.Text = regex.Replace(textBox.Text, "");
            }
        }


        //按Delete，删除一项
        private void listView_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Delete)
            {
                ListView listview = (ListView)sender;
                Teshu_gas_item? teshu_Gas_Item = listview.SelectedItem as Teshu_gas_item;
                if (teshu_Gas_Item == null)
                {
                    e.Handled = true;
                    return;
                }

                //执行删除
                var result = teshuBusiness.DeleteTeshuGasItem(teshu_Gas_Item.Id);
                ShowAlertHelpter.ShowAlert(result.Msg);
                if (result.Code == (int)ResultCode.Success)
                {
                    var list = teshuBusiness.GetTeshu_gas_itemList(TeshuGas.Id);
                    this.listView.ItemsSource = list;
                }
            }
        }

        //校对  //创建时间：2022-12-21 17:25:18。
        private void jiaodui_Click(object sender, RoutedEventArgs e)
        {
            Teshu_gas teshu_Gas = new Teshu_gas();
            teshu_Gas.Id = TeshuGas.Id;
            teshu_Gas.Report_no = txt_report_no.Text.Trim();
            teshu_Gas.Sample_temperature = txtSample_temperature.Text.Trim().ToMyDecimal();
            teshu_Gas.Oil_pressure = txtOil_pressure.Text.Trim().ToMyDecimal();
            teshu_Gas.Client = cmb_client.SelectedValue?.ToString();
            teshu_Gas.Sampling_unit = cmb_sampling_unit.SelectedValue?.ToString();

            teshu_Gas.Well_no = txt_well_no.Text.Trim();
            teshu_Gas.Top_boundary = cmb_top_boundary.SelectedValue?.ToString();
            teshu_Gas.Casing_pressure = txt_casing_pressure.Text.Trim().ToMyDecimal();
            teshu_Gas.Sampler = cmb_sampler.SelectedValue?.ToString();
            teshu_Gas.Sampling_time = date_sampling_time.Text;

            teshu_Gas.Well_deep = txt_well_deep.Text.Trim();
            teshu_Gas.Bottom_boundary = cmb_bottom_boundary.SelectedValue?.ToString();
            teshu_Gas.Sampling_location = cmb_sampling_location.SelectedValue?.ToString();
            teshu_Gas.Analyst = cmb_analyst.SelectedValue?.ToString();

            var result = teshuBusiness.Proofread(teshu_Gas);
            ShowAlertHelpter.ShowAlert(result.Msg);
            if (result.Code == (int)ResultCode.Success)
            {
                RefreshPageList?.Invoke(this, e);
                this.Close();
            }
        }
    }
}
